from django.contrib.auth.models import Group
from rest_framework.permissions import BasePermission


class TeacherPermissions(BasePermission):
    """
    老师权限，只有老师登录才可以查看班级情况
    """

    def has_permission(self, request, view):
        user = request.user  # 先拿到用户
        group = Group.objects.get(name='老师组')  # 拿到老师组
        groups = user.groups.all()  # 获取用户所在的组,正向操作
        return bool(user.is_superuser or group in groups)


class ActiveUserPermissions(BasePermission):
    """
    当前登录用户只能操作当前的用户相关功能
    """
    def has_permission(self, request, view):
        user = request.user
        # 当前登录用户的id：user.id，想要操作的用户id：
        return user.id == int(view.kwargs['pk'])


class MyBasePermissions(BasePermission):
    def has_permission(self, request, view):
        if view.action == 'destroy':  # 删除数据的接口权限设置，注意，一定要放在最前面
            return request.user.is_superuser

        if request.method in ['GET', 'HEAD', 'OPTION']:  # 查找数据的接口权限设置
            return True

        if request.user.is_superuser:  # 查找数据的接口权限设置
            return True

        if view.action in ['create' or 'update']:  # 增加数据接口的权限设置，同时要在视图重写增加数据接口的方法 or 修改权限，同时再视图重写方法
            user = request.user
            group = Group.objects.filter(name='老师组').first()
            groups = user.groups.all()
            return bool(user.is_superuser or group in groups)


# 装饰器，权限许多相同的代码可以写在一起变成装饰器
def auto_user(func):
    def f(self, request, *args, **kwargs):
        request.POST._mutable = True
        request.data['user'] = str(request.user.id)
        return func(self, request, *args, **kwargs)
    return f